import { createRouter, createWebHistory } from 'vue-router'
import { useModalStore } from '@/stores/modal'
import { useUserStore } from '@/stores/user'
import { message } from '@/utils/message'

const routes = [
  {
    path: '/',
    name: 'index',
    component: () => import('@/views/Index/index.vue'),
    //meta: { requiresAuth: true } // 需要登录
  },
  {
    path: '/forum',
    name: 'forum',
    component: () => import('@/views/Forum/index/index.vue'),
  },
  {
    path: '/forum/details/:id',
    name: 'forumDetails',
    component: () => import('@/views/Forum/details/index.vue'),
  },
  {
    path: '/forum/search',
    name: 'forumSearch',
    component: () => import('@/views/Forum/search/index.vue'),
  },
  {
    path: '/forum/create',
    name: 'forumCreate',
    component: () => import('@/views/Forum/create/index.vue'),
    // meta: { requiresAuth: true }
  },
  {
    path: '/forum/my-posts',
    name: 'myPosts',
    component: () => import('@/views/Forum/my-posts/index.vue'),
    meta: { requiresAuth: true }
  },

  {
    path: '/project',
    name: 'project',
    component: () => import('@/views/Project/index.vue'),
  },
  {
    path: '/shop',
    name: 'shop',
    component: () => import('@/views/Shop/index.vue'),
  },

]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  // 如果需要登录，并且用户信息不存在，则打开登录弹窗
  if (to.meta.requiresAuth && !userStore.isLogin()) {
    const modalStore = useModalStore()
    message.primary('请先登录')
    modalStore.openLoginModal()
  } else {
    next()
  }
})
export default router
